package controllers

import (
	"admin-glm-go/internal/models"
	"admin-glm-go/internal/response"
	"admin-glm-go/internal/utils"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// PermissionListRequest 权限列表请求参数
type PermissionListRequest struct {
	Page     int    `form:"page"`
	PageSize int    `form:"pageSize"`
	Name     string `form:"name"`
	Type     int    `form:"type"`
}

// AddPermissionRequest 添加权限请求参数
type AddPermissionRequest struct {
	Name       string `json:"name" binding:"required"`
	Code       string `json:"code" binding:"required"`
	Type       int    `json:"type" binding:"required"`
	Icon       string `json:"icon"`
	Path       string `json:"path"`
	Component  string `json:"component"`
	Permission string `json:"permission"`
	Sort       int    `json:"sort"`
	ParentID   uint64 `json:"parentId"`
	Status     int    `json:"status"`
}

// UpdatePermissionRequest 更新权限请求参数
type UpdatePermissionRequest struct {
	ID         uint64 `json:"id" binding:"required"`
	Name       string `json:"name" binding:"required"`
	Code       string `json:"code" binding:"required"`
	Type       int    `json:"type" binding:"required"`
	Icon       string `json:"icon"`
	Path       string `json:"path"`
	Component  string `json:"component"`
	Permission string `json:"permission"`
	Sort       int    `json:"sort"`
	ParentID   uint64 `json:"parentId"`
	Status     int    `json:"status"`
}

// PermissionController 权限控制器
type PermissionController struct {
	db *gorm.DB
}

// NewPermissionController 创建权限控制器
func NewPermissionController(db *gorm.DB) *PermissionController {
	return &PermissionController{db: db}
}

// GetPermissionList 获取权限列表
// @Summary 获取权限列表
// @Description 获取权限列表
// @Tags 权限管理模块
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Param page query int false "页码"
// @Param pageSize query int false "每页数量"
// @Param name query string false "权限名称"
// @Param type query int false "权限类型"
// @Success 200 {object} response.Response
// @Router /permission/list [get]
func (ctrl *PermissionController) GetPermissionList(c *gin.Context) {
	var req PermissionListRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		response.ParamError(c)
		return
	}

	// 设置默认值
	if req.Page <= 0 {
		req.Page = 1
	}
	if req.PageSize <= 0 {
		req.PageSize = 10
	}

	// 构建查询条件
	query := ctrl.db.Model(&models.Permission{})
	if req.Name != "" {
		query = query.Where("name LIKE ?", "%"+req.Name+"%")
	}
	if req.Type != 0 {
		query = query.Where("type = ?", req.Type)
	}

	// 获取总数
	var total int64
	query.Count(&total)

	// 分页查询
	var permissions []models.Permission
	offset := (req.Page - 1) * req.PageSize
	err := query.Offset(offset).Limit(req.PageSize).Order("sort ASC, id ASC").Find(&permissions).Error
	if err != nil {
		response.ServerError(c)
		return
	}

	// 构建响应数据
	var records []gin.H
	for _, permission := range permissions {
		record := gin.H{
			"id":         permission.ID,
			"name":       permission.Name,
			"code":       permission.Code,
			"type":       permission.Type,
			"icon":       permission.Icon,
			"path":       permission.Path,
			"component":  permission.Component,
			"permission":  permission.Permission,
			"sort":       permission.Sort,
			"parentId":   permission.ParentID,
			"status":     permission.Status,
			"createTime": permission.CreateTime.Format("2006-01-02 15:04:05"),
			"updateTime": permission.UpdateTime.Format("2006-01-02 15:04:05"),
		}
		records = append(records, record)
	}

	response.PageSuccess(c, total, records, req.Page, req.PageSize)
}

// GetPermissionTree 获取权限树
// @Summary 获取权限树
// @Description 获取权限树
// @Tags 权限管理模块
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Success 200 {object} response.Response
// @Router /permission/tree [get]
func (ctrl *PermissionController) GetPermissionTree(c *gin.Context) {
	var permissions []models.Permission
	if err := ctrl.db.Order("sort ASC, id ASC").Find(&permissions).Error; err != nil {
		response.ServerError(c)
		return
	}

	// 构建树形结构
	tree := buildPermissionTree(permissions, 0)

	response.Success(c, tree)
}

// buildPermissionTree 构建权限树
func buildPermissionTree(permissions []models.Permission, parentId uint64) []gin.H {
	var tree []gin.H

	for _, permission := range permissions {
		if permission.ParentID == parentId {
			node := gin.H{
				"id":         permission.ID,
				"name":       permission.Name,
				"code":       permission.Code,
				"type":       permission.Type,
				"icon":       permission.Icon,
				"path":       permission.Path,
				"component":  permission.Component,
				"permission": permission.Permission,
				"sort":       permission.Sort,
				"parentId":   permission.ParentID,
				"status":     permission.Status,
				"createTime": permission.CreateTime.Format("2006-01-02 15:04:05"),
				"updateTime": permission.UpdateTime.Format("2006-01-02 15:04:05"),
			}

			// 递归构建子节点
			children := buildPermissionTree(permissions, permission.ID)
			if len(children) > 0 {
				node["children"] = children
			}

			tree = append(tree, node)
		}
	}

	return tree
}

// AddPermission 添加权限
// @Summary 添加权限
// @Description 添加权限
// @Tags 权限管理模块
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Param body body AddPermissionRequest true "权限信息"
// @Success 200 {object} response.Response
// @Router /permission/add [post]
func (ctrl *PermissionController) AddPermission(c *gin.Context) {
	var req AddPermissionRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.ParamError(c)
		return
	}

	// 检查权限名称是否已存在
	var count int64
	if err := ctrl.db.Model(&models.Permission{}).Where("name = ?", req.Name).Count(&count).Error; err != nil {
		response.ServerError(c)
		return
	}
	if count > 0 {
		response.Error(c, 400, "权限名称已存在")
		return
	}

	// 检查权限编码是否已存在
	if err := ctrl.db.Model(&models.Permission{}).Where("code = ?", req.Code).Count(&count).Error; err != nil {
		response.ServerError(c)
		return
	}
	if count > 0 {
		response.Error(c, 400, "权限编码已存在")
		return
	}

	// 如果有父级ID，检查父级是否存在
	if req.ParentID > 0 {
		var parent models.Permission
		if err := ctrl.db.First(&parent, req.ParentID).Error; err != nil {
			response.Error(c, 400, "父级权限不存在")
			return
		}
	}

	// 创建权限
	permission := models.Permission{
		Name:       req.Name,
		Code:       req.Code,
		Type:       req.Type,
		Icon:       req.Icon,
		Path:       req.Path,
		Component:  req.Component,
		Permission: req.Permission,
		Sort:       req.Sort,
		ParentID:   req.ParentID,
		Status:     req.Status,
	}

	// 保存权限
	if err := ctrl.db.Create(&permission).Error; err != nil {
		response.ServerError(c)
		return
	}

	response.Success(c, nil)
}

// UpdatePermission 更新权限
// @Summary 更新权限
// @Description 更新权限
// @Tags 权限管理模块
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Param body body UpdatePermissionRequest true "权限信息"
// @Success 200 {object} response.Response
// @Router /permission/update [put]
func (ctrl *PermissionController) UpdatePermission(c *gin.Context) {
	var req UpdatePermissionRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.ParamError(c)
		return
	}

	// 查询权限
	var permission models.Permission
	if err := ctrl.db.First(&permission, req.ID).Error; err != nil {
		response.NotFound(c)
		return
	}

	// 检查权限名称是否已存在（排除自己）
	var count int64
	if err := ctrl.db.Model(&models.Permission{}).Where("name = ? AND id != ?", req.Name, req.ID).Count(&count).Error; err != nil {
		response.ServerError(c)
		return
	}
	if count > 0 {
		response.Error(c, 400, "权限名称已存在")
		return
	}

	// 检查权限编码是否已存在（排除自己）
	if err := ctrl.db.Model(&models.Permission{}).Where("code = ? AND id != ?", req.Code, req.ID).Count(&count).Error; err != nil {
		response.ServerError(c)
		return
	}
	if count > 0 {
		response.Error(c, 400, "权限编码已存在")
		return
	}

	// 如果有父级ID，检查父级是否存在且不能是自己或自己的子级
	if req.ParentID > 0 {
		// 不能设置自己为父级
		if req.ParentID == req.ID {
			response.Error(c, 400, "不能设置自己为父级")
			return
		}

		// 检查父级是否存在
		var parent models.Permission
		if err := ctrl.db.First(&parent, req.ParentID).Error; err != nil {
			response.Error(c, 400, "父级权限不存在")
			return
		}

		// 检查是否设置自己的子级为父级（防止循环引用）
		var childIds []uint64
		getAllChildIds(ctrl.db, req.ID, &childIds)
		if utils.ContainsUint64(childIds, req.ParentID) {
			response.Error(c, 400, "不能设置自己的子级为父级")
			return
		}
	}

	// 更新权限信息
	permission.Name = req.Name
	permission.Code = req.Code
	permission.Type = req.Type
	permission.Icon = req.Icon
	permission.Path = req.Path
	permission.Component = req.Component
	permission.Permission = req.Permission
	permission.Sort = req.Sort
	permission.ParentID = req.ParentID
	permission.Status = req.Status

	// 保存权限
	if err := ctrl.db.Save(&permission).Error; err != nil {
		response.ServerError(c)
		return
	}

	response.Success(c, nil)
}

// DeletePermission 删除权限
// @Summary 删除权限
// @Description 删除权限
// @Tags 权限管理模块
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Param id path int true "权限ID"
// @Success 200 {object} response.Response
// @Router /permission/delete/{id} [delete]
func (ctrl *PermissionController) DeletePermission(c *gin.Context) {
	id := utils.StringToUint64(c.Param("id"))
	if id == 0 {
		response.ParamError(c)
		return
	}

	// 查询权限
	var permission models.Permission
	if err := ctrl.db.First(&permission, id).Error; err != nil {
		response.NotFound(c)
		return
	}

	// 检查是否有子权限
	var count int64
	if err := ctrl.db.Model(&models.Permission{}).Where("parent_id = ?", id).Count(&count).Error; err != nil {
		response.ServerError(c)
		return
	}
	if count > 0 {
		response.Error(c, 400, "请先删除子权限")
		return
	}

	// 删除权限
	if err := ctrl.db.Delete(&permission).Error; err != nil {
		response.ServerError(c)
		return
	}

	response.Success(c, nil)
}

// getAllChildIds 获取所有子权限ID
func getAllChildIds(db *gorm.DB, parentId uint64, childIds *[]uint64) {
	var children []models.Permission
	if err := db.Where("parent_id = ?", parentId).Find(&children).Error; err != nil {
		return
	}

	for _, child := range children {
		*childIds = append(*childIds, child.ID)
		getAllChildIds(db, child.ID, childIds)
	}
}